//
//  2. 两数相加.swift
//  Top600
//
//  Created by rjb on 2021/8/10.
//

import Foundation
class Solution2 {
    // 两数相加
    func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        let vHead = ListNode(-1)
        
        var p:ListNode? = vHead
        var cur1 = l1
        var cur2 = l2
        
        var flag: Int = 0 // 是否进位
        while cur1 != nil || cur2 != nil {
            var tmpSum = 0
            if let cur1 = cur1 {
                tmpSum += cur1.val
            }
            if let p2 = cur2 {
                tmpSum += p2.val
            }
            tmpSum += flag // 与进位相加
            flag = tmpSum / 10 // 计算进位
            tmpSum = tmpSum % 10 // 计算本位值
            // 加入节点
            let node = ListNode(tmpSum)
            p?.next = node
            p = p?.next
            
            cur1 = cur1?.next
            cur2 = cur2?.next
        }
        if flag == 1 {
            let node = ListNode(1)
            p?.next = node
            p = p?.next
        }
        return vHead.next
    }
    static func test() {
        let node1 = ListNode(2)
        let node4 = ListNode(4)
        let node3 = ListNode(3)
        node1.next = node4
        node4.next = node3
        
        let node5 = ListNode(5)
        let node6 = ListNode(6)
        let node44 = ListNode(4)
        node5.next = node6
        node6.next = node44
        
        let solution = Solution2()
        let result = solution.addTwoNumbers(node1, node5)
        print(result)
    }
}
